package humynn.sbd
{
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * A class to load and store the game tips.
	 */
	public class Tips
	{
		private static var _tips:Array;
		private static var _loader:URLLoader;
		private static var _workingTips:Array;
		
		public function Tips()
		{
		}
		
		/**
		 * Begins to load the tips from the info.txt file.
		 */
		public static function loadTips():void
		{
			_tips = new Array();
			_workingTips = new Array();
			
			_loader = new URLLoader();
			_loader.addEventListener(Event.COMPLETE, loaded);
			_loader.load(new URLRequest("data/info.txt"));
		}
		
		/**
		 * Grabs random tips for use throughout the game and provides
		 * an easy way to randomize tips for a second play-through.
		 * 
		 * @param max The maximum number of tips needed for a complete game.
		 */
		public static function randomize(max:int):void
		{
			var _tipsCopy:Array = _tips;
			_workingTips = new Array();
			
			for(var i:int = 0; i < max; i++)
			{
				var r:int = Math.floor(Math.random() * _tipsCopy.length);
				
				_workingTips.push(_tipsCopy[r]);
				_tipsCopy.splice(r, 1);
			}
		}
		
		/**
		 * Gets the title of the tip at the given index.
		 * 
		 * @param index The tip index to look up.
		 */
		public static function getTipTitle(index:int):String
		{
			return _workingTips[index]["title"];
		}
		
		/**
		 * Gets the body of the tip at the given index.
		 * 
		 * @param index The tip index to look up.
		 */
		public static function getTipBody(index:int):String
		{
			return _workingTips[index]["body"];
		}
		
		/**
		 * Stores the tips from the loaded file.
		 * 
		 * @param e Ignored.
		 */
		private static function loaded(e:Event):void
		{
			var lines:Array = String(_loader.data).split("\r\n");
			
			for each(var line:String in lines)
			{
				var parts:Array = line.split(":");
				
				var tip:Object = new Object();
				tip["title"] = parts[0];
				tip["body"] = parts[1];
				
				_tips.push(tip);
			}
		}
	}
}